(use-modules ((tcp-server) #:prefix server:)
             (ice-9 textual-ports)
             (json))


(define (json-echo-message-handler client-connection scm-native)
  (let ([in-out-sock (car client-connection)])
    (display (simple-format #f "RECEIVED JSON: ~s, which is: ~s\n"
                            scm-native
                            (scm->json-string scm-native)))
    (scm->json scm-native in-out-sock)
    (force-output in-out-sock)
    (display (simple-format #f "SENT JSON: ~s, which is: ~s\n"
                            scm-native
                            (scm->json-string scm-native)))))

(define json-echo-protocol
  (server:make-server-protocol
   #:port-reader json->scm
   #:message-handler json-echo-message-handler
   #:eof-handler server:shutdown-client-connection))


;; JSON ECHO SERVER
(define server-sock
  (server:run-server 12345
                     #:protocol json-echo-protocol))


;; To run this you need to add the containing directory to the load path.
;; (add-to-load-path "YOUR DIRECTORY HERE")
